package org.deng.learn.async;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author 邓力宾
 * @date 2020/12/18 13:52
 * @desc 异步servlet 耗时操作交给单独的线程处理，不会阻塞当前servlet线程，servlet线程可以处理更多的请求
 */
@WebServlet(value = "/asyncServlet", asyncSupported = true) //开启异步
public class AsyncServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AsyncContext context = req.startAsync();//开启异步
        long s = System.currentTimeMillis();
        CompletableFuture.runAsync(()->{
            try {
                //模拟耗时操作
                TimeUnit.SECONDS.sleep(3);
                resp.getWriter().write("success");
                context.complete();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        System.out.println("used:"+(System.currentTimeMillis() - s));
    }
}
